<?php

namespace App\Admin\Controllers;

use App\Library\Model\DemoModel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Show;

class DemoController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = 'Example controller';

    /**
     * grid
     * @return Grid
     */
    protected function grid(): Grid
    {
        $grid = new Grid(new DemoModel);
        $grid->column('id')->sortable();
        $grid->column('serial_number', '序列号');
        $grid->column('switch', '开关')->using([0 => '关闭', 1 => '开启']);
        $grid->column('title', '标题');
        $grid->column('quantity', '数量');
        $grid->column('created_at', '创建时间');
        $grid->actions(function (Actions $action) {
            $action->disableDelete(false);
            $action->disableView(false);
        });
        $grid->disableCreateButton(false);
        $grid->disableActions(false);
        return $grid;
    }

    /**
     * detail
     * @param mixed $id
     * @return Show
     */
    protected function detail(int $id): Show
    {
        $show = new Show(DemoModel::findOrFail($id));

        $show->field('id', __('ID'));
        $show->field('switch', '开关')->using([0 => '关闭', 1 => '开启']);
        $show->field('title', '标题');
        $show->field('quantity', '数量');
        $show->field('remark', '备注');
        $show->field('created_at', '创建时间');
        return $show;
    }

    /**
     * form
     * @return Form
     */
    protected function form(): Form
    {
        $form = new Form(new DemoModel);

        $form->hidden('serial_number');

        $form->display('id', __('ID'));
        $form->select('switch', '开关')->options([0 => '关闭', 1 => '开启'])->default(0)->required();
        $form->text('title', '标题')->required();
        $form->number('quantity', '数量')->default(0)->required();
        $form->textarea('remark', '备注');
        $form->saving(function (Form $form) {
            if ($form->isCreating()) $form->serial_number = DemoModel::getSerialNumber();
        });
        return $form;
    }
}
